using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using HCore.IOC.Beans.Factory;
using HCore.IOC.Beans.Factory.Attribute.Attr;
using HCore.IOC.Context.Event.Attr;
using HCore.Tests.Runtime.DianDianDian.Event;
using HCore.Tests.Runtime.DianDianDian.Model;
using UnityEngine;

namespace HCore.Tests.Runtime.DianDianDian.System
{
    public class AchievementItem
    {
        // 成就名称
        public string Name { get; set; }

        // 达成条件
        public Func<bool> CheckComplete { get; set; }

        // 是否已解锁
        public bool Unlocked { get; set; }
    }

    [IOC.Context.Stereotype.Component]
    public class AchievementSystem : IInitializingBean
    {
        private readonly List<AchievementItem> mItems = new();
        [Autowired] private IGameModel mGameModel;
        private bool mMissed;

        public void AfterPropertiesSet()
        {
            mItems.Add(new AchievementItem
            {
                Name = "满分",
                CheckComplete = () => mGameModel.BestScore >= 100
            });

            mItems.Add(new AchievementItem
            {
                Name = "手残党",
                CheckComplete = () => mGameModel.Score < 0
            });

            mItems.Add(new AchievementItem
            {
                Name = "零失误",
                CheckComplete = () => !mMissed
            });

            mItems.Add(new AchievementItem
            {
                Name = "成就达人",
                CheckComplete = () => mItems.Count(item => item.Unlocked) >= 3
            });

            mItems.Add(new AchievementItem
            {
                Name = "完美通关",
                CheckComplete = () => mGameModel.BestScore >= 100 && !mMissed
            });
        }


        [EventListener]
        private void OnMissEvent(MissEvent @event)
        {
            mMissed = true;
        }


        [EventListener]
        private void OnGameStartEvent(GameStartEvent @event)
        {
            mMissed = false;
        }

        // 成就系统一般是持久化的，如果需要，可以在这里进行
        [EventListener]
        private async void OnGamePassEvent(GamePassEvent @event)
        {
            // 这里延迟执行是为了所有事情完成后在做，先这样处理呗
            Debug.Log($"async start: {DateTime.Now}");
            await Task.Delay(TimeSpan.FromSeconds(1f));
            Debug.Log($"async end: {DateTime.Now}");

            Debug.Log("完成成就：");
            foreach (var achievementItem in mItems.Where(achievementItem => !achievementItem.Unlocked && achievementItem.CheckComplete()))
            {
                achievementItem.Unlocked = true;
                Debug.Log($"成就：{achievementItem.Name}");
            }
        }
    }
}